package com.fjwt.gz.coupon.gtpay;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.ServiceException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.rmi.server.ExportException;
import java.util.Map;

import static com.fjwt.gz.coupon.gtpay.demo.MktSignUtil.createSign;

@Service
@Slf4j
public class GtpayCouponNotifyService {

    private static final Logger gtPayLogger = LoggerFactory.getLogger("gtPay");

    private static String logPrefix = "国通卡券核销回调:";

    public static String gtKey = "Dl0AG8wdp45F";

    public Map<String, Object> paraseParamters(HttpServletRequest request, NotificationConfig notificationConfig) throws IOException {
        String body = this.getBody(request);
        log.info("gt解析出来的参数是：{}", body);
        JSONObject jsonObject = JSONObject.parseObject(body);
        String sign = jsonObject.getString("sign");
        jsonObject.remove("sign");
        gtPayLogger.info(logPrefix + "request:{}", body);
        String signs = createSign(com.alibaba.fastjson.JSONObject.parseObject(String.valueOf(jsonObject)), gtKey);
        log.info("gt签名：{}", signs);
        if (!signs.equals(sign)) {
            throw new ExportException("签名错误");
        }
        // 如果没有加密数据，则继续解析其他参数
        Map<String, Object> map = jsonObject;
        gtPayLogger.info(logPrefix + "解析参数返回的信息是：{}", JSONUtil.toJsonStr(map));
        return map;
    }


    protected final String getBody(HttpServletRequest request) {
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8);
            StringBuffer bf = new StringBuffer();
            int len;
            char[] chs = new char[1024];
            while ((len = in.read(chs)) != -1) {
                bf.append(new String(chs, 0, len));
            }
            return bf.toString();
        } catch (Exception e) {
            log.error("请求头部取数据异常：{}", e.getMessage());
            throw new ServiceException(e.getMessage());
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (Exception e) {
                    log.error("流关闭异常:{}", e.getMessage());
                }
            }
        }
    }
}
